package com.xyzh05.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xyzh05.dao.EditorDao;
import com.xyzh05.dao.PricingDao;
import com.xyzh05.dao.TransactionDao;
import com.xyzh05.dao.TransactionEntryDao;
import com.xyzh05.dao.VipServiceDao;
import com.xyzh05.dao.VipServiceTransactionDao;
import com.xyzh05.model.Editor;
import com.xyzh05.model.Order;
import com.xyzh05.model.Pricing;
import com.xyzh05.model.Transaction;
import com.xyzh05.model.TransactionEntry;
import com.xyzh05.model.User;
import com.xyzh05.model.VipService;
import com.xyzh05.model.VipServiceTransaction;
import com.xyzh05.service.TransactionEntryManager;
import com.xyzh05.util.PageBean;

@Service("transactionEntryManager")
@WebService(serviceName = "TransactionEntryService", endpointInterface = "com.xyzh05.service.TransactionEntryManager")
public class TransactionEntryManagerImpl extends GenericManagerImpl<TransactionEntry, Long> implements TransactionEntryManager {
    TransactionEntryDao transactionEntryDao;
    
    private EditorDao editorDao;
    
    private TransactionDao transactionDao ;
    
    private VipServiceDao vipServiceDao;
    
    private VipServiceTransactionDao vipServiceTransactionDao; 
    
    private PricingDao pricingDao;

    @Autowired
    public TransactionEntryManagerImpl(TransactionEntryDao transactionEntryDao ,EditorDao editorDao , TransactionDao transactionDao  , VipServiceDao vipServiceDao ,VipServiceTransactionDao vipServiceTransactionDao ,PricingDao pricingDao) {
        super(transactionEntryDao);
        this.transactionEntryDao = transactionEntryDao;
        this.editorDao=editorDao;
        this.transactionDao=transactionDao;
        this. vipServiceDao= vipServiceDao;
        this.vipServiceTransactionDao=vipServiceTransactionDao;
        this.pricingDao=pricingDao;
    }



	public PageBean findList(PageBean pageBean,
			TransactionEntry transactionEntry ,Long vipServiceId) {
		StringBuilder sb = new StringBuilder();
		List list = new ArrayList();
		sb.append("select vs from TransactionEntry vs left join vs.vipServiceTransaction vst where vst.vipService.id = "+vipServiceId);
		
		
		if(pageBean != null){
			if (pageBean.getSortCriterion() != null) {
				sb.append(" order by ");
				sb.append(pageBean.getSortCriterion()+" ");			
			}
			if (pageBean.getSortParamDirection() != null) {
				sb.append(pageBean.getSortParamDirection());			
			}
		}
		
		return transactionEntryDao.getPageByHQL(sb.toString(), pageBean, list.toArray());
	}

	/**
	 * 创建文书交易
	 * @param client 定单客户
	 * @param orders 文书定单
	 * @param state 交易状态。新交易: Transaction.NEW, 未支付: Transaction.PAY, 已支付: Transaction.START
	 * @return
	 * @throws Exception 编辑空闲点数不够
	 */
	public Transaction checkout(User user, List<Order> orders, int state , Long vipServiceId ) throws Exception {
		try {
			// 检查编辑空闲点数
			Map<Editor, Integer> points = new HashMap<Editor, Integer>();
			for (Order order : orders) {
				if (!points.containsKey(order.getEditor()))
					points.put(order.getEditor(), 0);
				Integer totalPoint = points.get(order.getEditor());
				totalPoint += order.getPricing().getService().getPoint();
				if (totalPoint > order.getEditor().getRemainIdle()) {
					// 超出空闲点数，无法购买
					throw new Exception("NOT_ENOUGH_IDLE");
				}
				points.put(order.getEditor(), totalPoint);
			}
			
			// TODO:更新编辑空闲点数
			for (Editor editor : points.keySet()) {
				editor.setRemainIdle(editor.getRemainIdle() - points.get(editor));
				editorDao.saveOrUpdate(editor);
			}
			
			// 生成交易
			Calendar calendar = Calendar.getInstance();
			Date startTime = calendar.getTime();
			int maxPeriod=0;
			Double totalPay = 0D;
			List<TransactionEntry> entries = new ArrayList<TransactionEntry>();
			
			TransactionEntry entry =null ; 
			
			VipService vipService =vipServiceDao.get(vipServiceId) ; 
			
			for (Order order : orders) {
				entry = new TransactionEntry();
				
				//TODO: 设置编辑关系
				entry.setEditor(order.getEditor());
				entry.setStartTime(startTime);
				entry.setFinishTime(startTime);
				
				// TODO
				// 修改：陶承恺
				// deadline为当前时间+服务时间+反馈时间
				calendar = Calendar.getInstance();
				calendar.add(Calendar.DATE, Integer.parseInt ( order.getPricing().getService().getPeriod()+order.getPricing().getService().getModifyPeriod().toString()));
				Date deadline = calendar.getTime();
				if((order.getPricing().getService().getPeriod()+order.getPricing().getService().getModifyPeriod())>maxPeriod)
				{
					maxPeriod= Integer.parseInt (order.getPricing().getService().getPeriod()+order.getPricing().getService().getModifyPeriod().toString());
				}

				entry.setDeadline(deadline);
				// TODO 设置编辑所得款
				Double payment = order.getPricing().getPrice();
				if (order.getPricing().getService().getStepPrice() > 0) {
					if (order.getSchoolNum() < 2)
						order.setSchoolNum(2);
					payment += order.getPricing().getService().getStepPrice() * (order.getSchoolNum() - 1);
				}
				entry.setPayment(payment);
				entry.setSchoolNum(new Long(order.getSchoolNum()));
				
				entry.setService(order.getPricing().getService());
				entry.setUser(vipService.getVip());
				entry.setFinished(false);
				entry.setStep(new Long(state));
				//entry.setTransaction(transaction);
				entries.add(entry);
				totalPay += entry.getPayment();
			}

			Transaction transaction = new Transaction();
			transaction.setStatus(new Long(state));
			transaction.setPayed(state == Transaction.START);
			transaction.setPayType(1);
			transaction.setPayment(totalPay);
			transaction.setUser(vipService.getVip());
			transaction.setStartTime(startTime);
			calendar = Calendar.getInstance();
			calendar.add(Calendar.DATE, maxPeriod);
			Date deadline = calendar.getTime();
			transaction.setDeadline(deadline);
			transaction.setFinishtime(startTime);
			transaction.setShowId(Order.newOrderId());
			transactionDao.save(transaction);
			
			entry.setTransaction(transaction);
			transactionEntryDao.save(entry);
			
			
			VipServiceTransaction v = new VipServiceTransaction();
			
			v.setUser(user);
			v.setTransactionEntry(entry);
			v.setvipService(vipServiceDao.get(vipServiceId));
			
			vipServiceTransactionDao.save(v);
			
			return transaction;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null ; 
		}
	}



	public String getBalance(Long vipServiceId) {
		
		VipService vipService = vipServiceDao.get(vipServiceId);
		
		if(vipService!=null&&vipService.getRepay()!=null){
			List <VipServiceTransaction> vs =vipServiceTransactionDao.getVSTbyVipService(vipServiceId);
			
			Double sum = new Double("0");
			
			for (VipServiceTransaction v : vs) {
				TransactionEntry t =transactionEntryDao.get(v.getTransactionEntry().getId());
				Pricing p = pricingDao.getPByEditorAService(t.getEditor().getUser().getId() , t.getService().getId());
				if (p!=null){
					sum+=p.getPrice();
				}
			}
			
			Double balane = new Double(vipService.getRepay())-sum;
			
			return balane.toString(); 
		}else{
			return null; 
		}
	}
}